<template>
  <!-- 添加或修改客户报修抢修对话框 -->
  <el-dialog title="预约工单" :visible.sync="open" width="860px" append-to-body>
    <el-form
      ref="CustomerRepairRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分配类型" prop="customerAuto">
            <el-select style="width:100%" v-model="form.customerAuto" placeholder="请选择分配类型">
              <el-option
                v-for="dict in dict.type.sys_fp"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务类型" prop="customerHelp">
            <el-select style="width:100%" v-model="form.customerHelp" placeholder="请选择服务类型">
              <el-option label="客户报修抢修" value="客户报修抢修"></el-option>
              <el-option label="线路委托运维" value="线路委托运维"></el-option>
              <el-option label="充电桩运维" value="充电桩运维"></el-option>
              <el-option label="配电室运维" value="配电室运维"></el-option>
              <el-option label="电子化移交" value="电子化移交"></el-option>
              <el-option label="高低压业扩" value="高低压业扩"></el-option>
              <el-option label="带电作业服务" value="带电作业服务"></el-option>
              <el-option label="电气设备预试" value="电气设备预试"></el-option>
              <el-option label="配电设备销售" value="配电设备销售"></el-option>
              <el-option label="临电共享服务" value="临电共享服务"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" v-if="false">
          <el-form-item label="用户id" prop="customerId">
            <el-input
              v-model.number="form.customerId"
              placeholder="请输入用户id"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发起人" prop="customerName">
            <el-input
              disabled
              v-model.number="form.customerName"
              placeholder="请输入发起人名称"
            />
            <!--              <el-select @change="getName" style="width:100%" v-model="form.customerId" placeholder="请选择用户名称" :loading="bLoad">-->
            <!--                <el-option-->
            <!--                  v-for="item in users"-->
            <!--                  :key="item.userId"-->
            <!--                  :label="`${item.nickName}【${item.userName}】`"-->
            <!--                  :value="item.userId"-->
            <!--                />-->
            <!--              </el-select>-->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发起人电话" prop="customerPhone">
            <el-input
              disabled
              v-model.number="form.customerPhone"
              placeholder="请输入发起人电话"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户姓名" prop="liaison">
            <el-input
              v-model.number="form.liaison"
              placeholder="请输入客户姓名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户电话" prop="liaisonPhone">
            <el-input
              v-model.number="form.liaisonPhone"
              placeholder="请输入客户电话"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="预约日期" prop="customerTimer">
            <el-date-picker
              style="width:100%"
              v-model="form.customerTimer"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预约时间段" prop="customerTimer">
            <el-time-picker
              is-range
              v-model="form.timeRange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围">
            </el-time-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="搜索位置">
        <baidu-map
          :scroll-wheel-zoom="true"
          style="width:100%;height:250px;display:flex;flex-direction: column-reverse;"
          :center="center"
          :zoom="zoom"
          @click="getLocation"
          @ready="handler">
          <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
          <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
          <div style="display:flex;margin-bottom: 15px">
            <bm-auto-complete v-model="searchAddress" :sugStyle="{zIndex: 999999}">
              <el-input v-model="searchAddress" style="width:620px;margin-right:15px" placeholder="输入地址进行搜索"></el-input>
            </bm-auto-complete>
            <el-button type="primary" @click="getBaiduMapPoint">搜索</el-button>
          </div>
          <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
          <bm-marker v-if="infoWindowShow" :position="{lng: longitude, lat: latitude}">
            <bm-label content="" :labelStyle="{color: 'red', fontSize : '24px'}" :offset="{width: -35, height: 30}"/>
          </bm-marker>
        </baidu-map>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="15">
          <el-form-item label="用户地址" prop="customerAddress">
            <el-input
              v-model="form.customerAddress"
              placeholder="请输入用户地址"
              @blur="changeAddress"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="经纬度" prop="lng">
            <el-input
              disabled
              v-model="form.lng"
              placeholder="请输入经纬度"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="问题阐述" prop="customerMessage">
            <el-input
              v-model="form.customerMessage"
              type="textarea"
              placeholder="请输入问题阐述"
            />
          </el-form-item>
        </el-col>
      </el-row>


      <el-form-item label="资料信息" prop="customerFiles">
        <file-upload :fileType="['doc', 'docx','xls', 'xlsx', 'ppt', 'pptx','txt', 'pdf', 'jpg', 'png', 'jpeg','zip','jar','rar']" :fileSize="100" v-model="form.customerFiles" />
      </el-form-item>

      <el-row :gutter="20" v-if="form.customerAuto == 2">
        <el-col :span="12">
          <el-form-item label="服务单位" prop="customerUnit">
            <treeselect @select="changeUnit" v-model="form.customerUnit" :options="frims" :normalizer="normalizer" placeholder="请选择服务单位" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务人员" prop="customerPlayer">
            <el-select multiple style="width:100%" v-model="form.customerPlayer" placeholder="请选择服务人员" :loading="bLoad">
              <el-option
                v-for="item in users"
                :key="item.userId"
                :label="`${item.nickName}【${item.userName}】`"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
        >立即预约</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listDept, listDeptExcludeChild } from '@/api/system/dept'
import { handleTree } from '@/utils/ruoyi'
import { addCustomerRepair, FrimUser, getCustomerRepair, updateCustomerRepair } from '@/api/web/CustomerRepair'
import { ba_gd } from '@/utils'
import moment from 'moment'
import { getInfo } from '@/api/login'

export default {
  name: "addOrder",
  dicts: ['sys_flag','sys_fp'],
  components: { Treeselect },
  // props: ['userInfo'],
  data() {
    return {
      searchAddress:'',
      infoWindowShow:false,
      longitude:'',
      latitude:'',
      center: {lng: 98.558011, lat: 24.451959}, // 定位位置116.413384, 39.910925
      zoom: 17, // 地图放大等级
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "",
      bLoad: false,
      users: [],
      frims: [],
      // 表单参数
      form: {
        customerAuto: '1'
      },
      buttonLoading: false,
      rules: {
        customerId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" },
        ],
        customerName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
        ],
        // liaison: [
        //   { required: true, message: "联系人姓名不能为空", trigger: "blur" },
        // ],
        // liaisonPhone: [
        //   { required: true, message: "联系人电话不能为空", trigger: "blur" },
        //   { type: 'number', message: '联系人电话必须为数字值'}
        // ],
        customerPhone: [
          { required: true, message: "用户电话不能为空", trigger: "blur" },
          // { type: 'number', message: '用户电话必须为数字值'}
        ],
        customerAddress: [
          { required: true, message: "用户地址不能为空", trigger: "blur" },
        ],
        customerHelp: [
          { required: true, message: "维修类型不能为空", trigger: "blur" },
        ],
        customerTimer: [
          { required: true, message: "选择日期不能为空", trigger: "blur" },
        ],
        customerMessage: [
          { required: true, message: "问题阐述不能为空", trigger: "blur" },
        ],
        customerFiles: [
          { required: true, message: "资料信息不能为空", trigger: "blur" },
        ],
        customerAuto: [
          { required: true, message: "分配类型不能为空", trigger: "change" },
        ],
        // customerUnit: [
        //   { required: true, message: "单位ID不能为空", trigger: "blur" },
        // ],
        // customerPlayer: [
        //   { required: true, message: "服务人员不能为空", trigger: "blur" },
        // ],
        customerFlag: [
          { required: true, message: "状态不能为空", trigger: "change" },
        ],
        customerKey: [{ required: true, message: "主键不能为空", trigger: "blur" }],
      },
    };
  },
  watch: {
  },
  created() {
  },
  methods: {
    /** 新增按钮操作 */
    handleAdd() {
      console.log('wwewe')
      this.reset();
      this.open = true;
      this.title = "添加客户报修抢修";
      // 查询第一级部门（易用能管理平台）
      listDept({ typeId: 1 }).then(response => {
        this.customDept = handleTree(response.data, "deptId");
      });
      // 查询服务商list
      listDept({ typeId: 3 }).then(response => {
        this.frims = handleTree(response.data, "deptId");
      });
      this.getInfo()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const customerKey = row.customerKey || ids;
      getCustomerRepair(customerKey).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改客户报修抢修";
      });
      if (row.customerUnit) {
        listDeptExcludeChild(row.customerUnit).then(response => {
          this.frims = handleTree(response.data, "deptId");
          const noResultsOptions = { deptId: this.form.parentId, deptName: this.form.parentName, children: [] };
          this.frims.push(noResultsOptions);
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["CustomerRepairRef"].validate((valid) => {
        // let item = this.form.lng.split(',')
        // let position = ba_gd(parseFloat(item[1]), parseFloat(item[0]))
        // console.log(this.form, 'hhhhh',position)
        if (valid) {
          if (!this.form.customerFiles) {
            this.$modal.msgError('请上传资料信息');
            return true
          }
          if (!this.form.lng) {
            this.$modal.msgError('请填写位置信息');
            return true
          }
          if (this.form.customerPlayer) {
            this.form.customerPlayer = this.form.customerPlayer.join(',')
          }
          let item = this.form.lng.split(',')
          let position = ba_gd(parseFloat(item[1]), parseFloat(item[0]))
          this.form.lat = position.lat
          this.form.lng = position.lng
          let temp = this.form.timeRange
          this.form.workOrderStatus = '0'
          this.form.customerFlag = 0
          console.log(moment(temp[0]).format('YYYY-MM-DD HH:mm:ss'), moment(temp[1]).format('YYYY-MM-DD HH:mm:ss'))
          // this.buttonLoading = true;
          this.form.customerTimer = `${moment(this.form.customerTimer).format('YYYY-MM-DD')} ${moment(temp[0]).format('HH:mm:ss')}至${moment(temp[1]).format('HH:mm:ss')}`
          console.log(this.form, '0000')
          if (this.form.customerKey != null) {
            updateCustomerRepair(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addCustomerRepair(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.$parent.getList();
              })
              .finally(() => {
                // this.$modal.msgError('工单预约失败');
                // this.buttonLoading = false;
              });
          }
        }
      });
    },
    // 调派单位选择变化
    changeUnit(value) {
      // this.dispatchForm.customerPlayer = null
      // console.log(typeof value, value.length, value[value.length -1], '值变化') // this.$refs['unit'].getCheckedNodes(),
      if (value && value.length !== 0) {
        let deptId = value.deptId
        FrimUser(deptId).then(res => {
          this.users = res.rows
          console.log(res, 'tttt')
        })
      }
    },
    getInfo() {
      getInfo().then(res => {
        // console.log(res)
        this.form.customerName = res.data.user.nickName
        this.form.customerPhone = res.data.user.phonenumber
        this.form.customerUnit = res.data.user.dept.deptId
        this.form.customerId = res.data.user.userId
        // const user = res.data.user
      }).catch(error => {
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 实例对象
    handler ({ BMap, map }) {
      const myGeo = new BMap.Geocoder();
      // 选择一个经纬度作为中心点
      this.point = new BMap.Point(98.558011, 24.451959); // 116.413384, 39.910925
      map.centerAndZoom(this.point, 17);
      this.BMap=BMap
      this.map=map
      const that = this
      myGeo.getLocation(this.point,function(result){
        console.log(result)
        that.form.customerAddress = result.address; //获取到当前定位的详细地址信息
        that.form.lng = `${result.point.lng},${result.point.lat}`
      });
    },
    //点击获取经纬度
    getLocation(e, key){
      console.log(e, '555')
      this.longitude=e.point.lng
      this.latitude=e.point.lat
      this.infoWindowShow=true
      this.center = {lng: e.point.lng, lat: e.point.lat}
      this.form.lng = `${e.point.lng},${e.point.lat}`
      const myGeo = new BMap.Geocoder();
      this.point = new BMap.Point(e.point.lng,e.point.lat); // 116.413384, 39.910925
      const that = this
      myGeo.getLocation(this.point,function(result){
        console.log(result)
        that.form.province = result.addressComponents.province
        that.form.city = result.addressComponents.city
        that.form.district = result.addressComponents.district
        // that.searchAddress = result.address
        that.form.customerCity = result.addressComponents.city
        if (!key) {
          that.form.customerAddress = result.address; //获取到当前定位的详细地址信息
        }
        if (result.surroundingPois && result.surroundingPois[0] && result.surroundingPois[0].point) {
          that.longitude=result.surroundingPois[0].point.lng
          that.latitude=result.surroundingPois[0].point.lat
          that.center = {lng: result.surroundingPois[0].point.lng, lat: result.surroundingPois[0].point.lat}
          that.form.lng = `${result.surroundingPois[0].point.lng},${result.surroundingPois[0].point.lat}`
          if (!key) {
            that.form.customerAddress = result.surroundingPois[0].address + (result.surroundingPois[0].title || ''); //获取到当前定位的详细地址信息
          }
        }
        // that.$set(that.form, 'address', result.address)
      });
    },
    getBaiduMapPoint() {
      console.log(this.searchAddress)
      let that=this
      that.form.customerAddress = this.searchAddress;
      let myGeo = new this.BMap.Geocoder()
      myGeo.getPoint(this.searchAddress,function(point){
        if(point){
          console.log(point)
          that.getLocation({ point: point }, 'key' )
          that.latitude=point.lat
          that.longitude=point.lng
          that.infoWindowShow=true
          that.center = {lng: point.lng, lat: point.lat}
          that.form.lng = `${point.lng},${point.lat}`
        }

      })
    },
    changeAddress(value) {
      console.log(this.form.customerAddress)
      let myGeo = new this.BMap.Geocoder()
      let that = this
      myGeo.getPoint(that.form.customerAddress,function(point){
        if(point){
          console.log(point)
          that.form.lng = `${point.lng},${point.lat}`
          that.point = new BMap.Point(point.lng,point.lat); // 116.413384, 39.910925
          myGeo.getLocation(that.point,function(result){
            console.log(result, 'qqq')
            that.form.province = result.addressComponents.province
            that.form.city = result.addressComponents.city
            that.form.district = result.addressComponents.district
            that.form.lng = `${result.point.lng},${result.point.lat}`
            // that.searchAddress = result.address
            that.form.customerCity = result.addressComponents.city
            // that.form.customerAddress = result.address; //获取到当前定位的详细地址信息
            that.$set(that.form, 'lng', `${result.point.lng},${result.point.lat}`)
          });
        }

      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        customerId: null,
        customerName: null,
        customerPhone: null,
        customerAddress: null,
        customerHelp: null,
        customerTimer: null,
        customerMessage: null,
        customerFiles: null,
        customerAuto: null,
        customerUnit: null,
        // customerPlayer: null,
        workOrderStatus: null,
        customerFlag: null,
        // createBy: null,
        // createTime: null,
        // updateBy: null,
        // updateTime: null,
        customerKey: null,
      };
      this.resetForm("CustomerRepairRef");
    },
  }
};
</script>

<style scoped>
/deep/ .el-form-item {
  margin-bottom: 16px!important;
}
/deep/.el-date-editor--datetimerange.el-input__inner {
  width: 320px;
}
/deep/.el-date-editor--timerange.el-input__inner {
  width: 295px;
}
</style>
